package com.yh.workbill.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yh.workbill.R;
import com.yh.workbill.databinding.ItemListDropDownBinding;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

public class TimeDropDownAdapter extends RecyclerView.Adapter<TimeDropDownAdapter.ViewHolder> {
    private Context context;
    private List<String> list;
    private int checkItemPosition = 0;
    private OnItemClick onItemClick;

    public void setOnItemClick(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public void setCheckItem(int position) {
        checkItemPosition = position;
        notifyDataSetChanged();
    }

    public TimeDropDownAdapter(Context context, List<String> data) {
        this.context = context;
        this.list = data;
    }

    public void setList(List<String> data) {
        this.list = data;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemListDropDownBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_list_drop_down, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        fillValue(position, holder);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    private void fillValue(int position, ViewHolder viewHolder) {
        String data = list.get(position);
        viewHolder.binding.setData(data);
        if (checkItemPosition != -1) {
            if (checkItemPosition == position) {
                viewHolder.binding.tvTime.setTextColor(context.getResources().getColor(R.color.colorAccent));
                viewHolder.binding.ivCheck.setVisibility(View.VISIBLE);
            } else {
                viewHolder.binding.tvTime.setTextColor(context.getResources().getColor(R.color.dialog_text));
                viewHolder.binding.ivCheck.setVisibility(View.GONE);
            }
        }
        viewHolder.itemView.setOnClickListener(v -> {
            if (onItemClick != null) {
                onItemClick.onItem(data, position);
            }
        });
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ItemListDropDownBinding binding;

        public ViewHolder(@NonNull ItemListDropDownBinding itemView) {
            super(itemView.getRoot());
            this.binding = itemView;
        }
    }

    public interface OnItemClick {
        void onItem(String data, int position);
    }
}
